package com.zx.config.jackson;

import com.zx.config.constant.MallConstant;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.text.SimpleDateFormat;

/**
 * @Description: JacksonObjectMapper
 * @Author: zhou hang
 * @CreateTime: 2015-07-17 11:03
 */
public class JacksonObjectMapper extends ObjectMapper {

    private Log logger = LogFactory.getLog(JacksonObjectMapper.class);

    public static String contentType = "application/json;charset=UTF-8";

    private static JacksonObjectMapper objectMapper;

    public static JacksonObjectMapper getInstance() {
        if (objectMapper == null) {
            synchronized (JacksonObjectMapper.class) {
                objectMapper = new JacksonObjectMapper();
                return objectMapper;
            }
        }
        return objectMapper;
    }

    public JacksonObjectMapper() {

        if (logger.isDebugEnabled()) {
            // 在调试模式下,格式化输出JSON
            configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        }

        configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, false);

        // 不予输出null字段
        setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);

        configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

        // 当数组中只有一个元素时，也按照数组输出
        configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

        // 时间格式化输出
        setDateFormat(new SimpleDateFormat(MallConstant.DATE_FORMAT));
    }
}